// API配置和基础请求方法
const API_BASE_URL = process.env.NODE_ENV === 'development' ? '/api' : 'http://localhost:3000/api';

// 统一的请求方法
const request = async (url, options = {}) => {
  const config = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers
    },
    ...options
  };

  try {
    const response = await fetch(`${API_BASE_URL}${url}`, config);
    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.message || '请求失败');
    }

    return data;
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
};

// 产品相关API
export const productAPI = {
  // 获取产品列表
  getProducts: (params = {}) => {
    const queryParams = new URLSearchParams(params).toString();
    return request(`/products?${queryParams}`);
  },

  // 获取单个产品详情
  getProduct: (id) => {
    return request(`/products/${id}`);
  },

  // 获取分类列表
  getCategories: () => {
    return request('/products/categories');
  },

  // 搜索产品
  searchProducts: (keyword, params = {}) => {
    return request(`/products?search=${encodeURIComponent(keyword)}&${new URLSearchParams(params).toString()}`);
  }
};

// 购物车相关API
export const cartAPI = {
  // 获取购物车
  getCart: () => {
    return request('/cart');
  },

  // 添加商品到购物车
  addToCart: (productId, quantity = 1) => {
    return request('/cart', {
      method: 'POST',
      body: JSON.stringify({ productId, quantity })
    });
  },

  // 更新购物车商品数量
  updateCartItem: (itemId, quantity) => {
    return request(`/cart/${itemId}`, {
      method: 'PUT',
      body: JSON.stringify({ quantity })
    });
  },

  // 删除购物车商品
  removeCartItem: (itemId) => {
    return request(`/cart/${itemId}`, {
      method: 'DELETE'
    });
  }
};

// 用户相关API
export const userAPI = {
  // 用户登录
  login: (email, password) => {
    return request('/auth/login', {
      method: 'POST',
      body: JSON.stringify({ email, password })
    });
  },

  // 用户注册
  register: (userData) => {
    return request('/auth/register', {
      method: 'POST',
      body: JSON.stringify(userData)
    });
  },

  // 获取用户信息
  getUserProfile: () => {
    return request('/users/profile');
  }
};

// 订单相关API
export const orderAPI = {
  // 获取订单列表
  getOrders: (params = {}) => {
    const queryParams = new URLSearchParams(params).toString();
    return request(`/orders?${queryParams}`);
  },

  // 创建订单
  createOrder: (orderData) => {
    return request('/orders', {
      method: 'POST',
      body: JSON.stringify(orderData)
    });
  },

  // 获取订单详情
  getOrder: (id) => {
    return request(`/orders/${id}`);
  }
};

export default request;